package com.andertrift.connectors;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import org.apache.log4j.Logger;

import twitter4j.FilterQuery;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;

public class TwitterConnector {
	private final String KEYWORDS[] = { "AnDerTrift" }; // Which tweets do you
														// want to filter?
	private final String ROOT = "C:\\"; // The rootfolder with the in and out
										// folder
	private Twitter twitter;
	private TwitterStream twitterStream;
	private LingWareHouseConnector lwh;
	private int counter = 0;
	private static Logger logger = Logger.getLogger(TwitterConnector.class);

	/**
	 * Constructor for the twitter connecter, this sets up the twitterstream
	 */
	public TwitterConnector() {
		twitter = new TwitterFactory().getInstance();
		twitterStream = new TwitterStreamFactory().getInstance();
		lwh = new LingWareHouseConnector();
		createStream();
	}

	/**
	 * Posts a message with given parameter
	 * 
	 * @param text
	 * @return
	 * @throws TwitterException
	 */
	public boolean postMessage(String text) {
		try {
			twitter.updateStatus(text);
			return true;
		} catch (TwitterException e) {
			logger.debug(e.getMessage());
			return false;
		}
	}

	/**
	 * Creates the Twitter stream which intercepts the messages with given
	 * keywords
	 */
	public void createStream() {
		try {
			StatusListener listener = new StatusListener() {
				@Override
				public void onStatus(Status status) {
					logger.debug("@" + status.getUser().getScreenName() + " - "
							+ status.getText());
					/*sendAutoReply(status); // Automatically sends a reply back*/
					saveFile(status); // saves the file
					postMessage("@" + status.getUser().getScreenName() + " "
							+ lwh.parseSentence((status.getText().replaceAll("@([A-Za-z0-9_]+)", ""))));
				}

				@Override
				public void onException(Exception ex) {
					logger.debug(ex.getMessage());
				}

				@Override
				public void onDeletionNotice(
						StatusDeletionNotice statusDeletionNotice) {
				}

				@Override
				public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
				}

				@Override
				public void onScrubGeo(long userId, long upToStatusId) {
				}

				@Override
				public void onStallWarning(StallWarning warning) {
				}
			};
			FilterQuery fq = new FilterQuery();
			fq.track(KEYWORDS);
			twitterStream.addListener(listener);
			twitterStream.filter(fq);
		} catch (Exception e) {

		}
	}

	/**
	 * Sends an automatic reply to the sender of a tweet (status)
	 * 
	 * @param status
	 */
	protected void sendAutoReply(Status status) {
		postMessage("@" + status.getUser().getScreenName()
				+ " bedankt voor uw reply!");
	}

	/**
	 * Saves the tweet (status) to a file so it can be processed
	 * 
	 * @param status
	 */
	private void saveFile(Status status) {
		try {
			BufferedWriter out = new BufferedWriter(
					new OutputStreamWriter(new FileOutputStream(ROOT
							+ "in\\test" + ++counter + ".txt"), "UTF-16"));
			out.write("title\n");
			out.write("date\n");
			out.write("author\n");
			out.write("source\n");
			out.write(status.getText().replace("@([A-Za-z0-9_]+)", ""));
			out.close();
		} catch (IOException e) {
			logger.debug(e.getMessage());
		}
	}
}
